package zengjin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import zengjin.common.BeanCopyUtil;
import zengjin.common.PageResponse;
import zengjin.mapper.*;
import zengjin.model.dto.interview.AddInterviewRequest;
import zengjin.model.dto.interview.PageInterviewRequest;
import zengjin.model.dto.interview.UpdateInterviewRequest;
import zengjin.model.en.*;
import zengjin.model.vo.interview.InterviewVO;
import zengjin.model.vo.interview.PageInterviewVO;
import zengjin.service.InterviewService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 19324
 * @description 针对表【interview】的数据库操作Service实现
 * @createDate 2025-02-23 21:28:34
 */
@Service
public class InterviewServiceImpl extends ServiceImpl<InterviewMapper, Interview>
        implements InterviewService {

    @Resource
    private InterviewMapper interviewMapper;

    @Resource
    private JobMapper jobMapper;

    @Resource
    private EmployerMapper employerMapper;

    @Resource
    private ResumeMapper resumeMapper;

    @Resource
    private ImageMapper imageMapper;

    @Override
    public Boolean addInterview(AddInterviewRequest addInterviewRequest) {
        //1.获取参数
        Long interviewJobseekerId = addInterviewRequest.getInterviewJobseekerId();
        Long interviewEmployerId = addInterviewRequest.getInterviewEmployerId();
        Long interviewJobId = addInterviewRequest.getInterviewJobId();
        String interviewStatus = addInterviewRequest.getInterviewStatus();
        String interviewType = addInterviewRequest.getInterviewType();
        String interviewLink = addInterviewRequest.getInterviewLink();
        Date interviewStartTime = addInterviewRequest.getInterviewStartTime();
        Date interviewEndTime = addInterviewRequest.getInterviewEndTime();
        String interviewRemarks = addInterviewRequest.getInterviewRemarks();

        //2.封装实体类
        Interview interview = new Interview();
        interview.setInterviewJobseekerId(interviewJobseekerId);
        interview.setInterviewEmployerId(interviewEmployerId);
        interview.setInterviewJobId(interviewJobId);
        interview.setInterviewStatus(interviewStatus);
        interview.setInterviewType(interviewType);
        interview.setInterviewLink(interviewLink);
        interview.setInterviewStartTime(interviewStartTime);
        interview.setInterviewEndTime(interviewEndTime);
        interview.setInterviewRemarks(interviewRemarks);

        //3.调用mapper层
        return interviewMapper.insert(interview) > 0;

    }

    @Override
    public Boolean updateInterview(UpdateInterviewRequest updateInterview) {
        //1.获取参数
        Long interviewId = updateInterview.getInterviewId();
        String interviewStatus = updateInterview.getInterviewStatus();
        String interviewType = updateInterview.getInterviewType();
        String interviewLink = updateInterview.getInterviewLink();
        Date interviewStartTime = updateInterview.getInterviewStartTime();
        Date interviewEndTime = updateInterview.getInterviewEndTime();
        String interviewRemarks = updateInterview.getInterviewRemarks();

        //2.更新面试信息
        LambdaUpdateWrapper<Interview> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Interview::getInterviewId, interviewId)
                .set(StrUtil.isNotBlank(interviewStatus), Interview::getInterviewStatus, interviewStatus)
                .set(StrUtil.isNotBlank(interviewType), Interview::getInterviewType, interviewType)
                .set(StrUtil.isNotBlank(interviewLink), Interview::getInterviewLink, interviewLink)
                .set(StrUtil.isNotBlank(interviewStartTime.toString()), Interview::getInterviewStartTime, interviewStartTime)
                .set(StrUtil.isNotBlank(interviewEndTime.toString()), Interview::getInterviewEndTime, interviewEndTime)
                .set(StrUtil.isNotBlank(interviewRemarks), Interview::getInterviewRemarks, interviewRemarks);
        return interviewMapper.update(null, updateWrapper) > 0;
    }

    @Override
    public PageResponse<PageInterviewVO> pageInterview(PageInterviewRequest pageInterviewRequest) {
        //1.获取参数
        String interviewJobseekerId = pageInterviewRequest.getInterviewJobseekerId();
        String interviewEmployerId = pageInterviewRequest.getInterviewEmployerId();
        String interviewStatus = pageInterviewRequest.getInterviewStatus();

        //2.判断是求职者查询，还是企业查询
        List<PageInterviewVO> pageInterviewVOS = new ArrayList<>();
        List<Interview> interviews = new ArrayList<>();
        if (StrUtil.isNotBlank(interviewJobseekerId)) {
            //求职者查询
            //查询出面试集合
            LambdaQueryWrapper<Interview> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Interview::getInterviewJobseekerId, interviewJobseekerId)
                    .eq(StrUtil.isNotBlank(interviewStatus), Interview::getInterviewStatus, interviewStatus);
            interviews = interviewMapper.selectList(queryWrapper);
            if("待面试".equals(interviewStatus)){
                for (int i = 0; i < interviews.size(); i++) {
                    Interview interview = interviews.get(i);
                    // 检查时间是否过期
                    if (interview.getInterviewEndTime().before(new Date())) {
                        // 更新状态为过期
                        LambdaUpdateWrapper<Interview> updateWrapper = new LambdaUpdateWrapper<>();
                        updateWrapper.eq(Interview::getInterviewId, interview.getInterviewId())
                                .set(Interview::getInterviewStatus, "已完成");
                        interviewMapper.update(null, updateWrapper);
                        interviews.remove(i);
                        i--; // 移除元素后，索引需要减 1
                    }
                }
            }
            interviews.forEach(interview -> {
                PageInterviewVO pageInterviewVO = BeanUtil.copyProperties(interview, PageInterviewVO.class);
                //查询出岗位
                LambdaQueryWrapper<Job> jobQueryWrapper = new LambdaQueryWrapper<>();
                jobQueryWrapper.eq(Job::getJobId, interview.getInterviewJobId());
                Job job = jobMapper.selectOne(jobQueryWrapper);
                pageInterviewVO.setJobTitle(job.getJobTitle());
                pageInterviewVO.setJobLocation(job.getJobLocation());
                pageInterviewVO.setJobType(job.getJobType());
                //查询出企业
                LambdaQueryWrapper<Employer> employerQueryWrapper = new LambdaQueryWrapper<>();
                employerQueryWrapper.eq(Employer::getEmployerId, interview.getInterviewEmployerId());
                Employer employer = employerMapper.selectOne(employerQueryWrapper);
                pageInterviewVO.setEmployerCompanyIndustry(employer.getEmployerCompanyIndustry());
                pageInterviewVO.setEmployerCompanyName(employer.getEmployerCompanyName());
                pageInterviewVO.setEmployerCompanyAddress(employer.getEmployerCompanyAddress());
                pageInterviewVO.setEmployerIsVerified(employer.getEmployerIsVerified());
                //查询头像
                QueryWrapper<Image> imageQueryWrapper = new QueryWrapper<>();
                imageQueryWrapper.eq("image_name", "employer_avatar");
                imageQueryWrapper.eq("image_name_id", employer.getEmployerId());
                Image image = imageMapper.selectOne(imageQueryWrapper);
                if (image != null) {
                    pageInterviewVO.setUserAvatarUrl(image.getImageUrl());
                }
                //添加到集合
                pageInterviewVOS.add(pageInterviewVO);
            });
        } else {
            //企业查询
            //查询出面试集合
            LambdaQueryWrapper<Interview> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Interview::getInterviewEmployerId, interviewEmployerId)
                    .eq(StrUtil.isNotBlank(interviewStatus), Interview::getInterviewStatus, interviewStatus);
            interviews = interviewMapper.selectList(queryWrapper);
            if("待面试".equals(interviewStatus)){
                for (int i = 0; i < interviews.size(); i++) {
                    Interview interview = interviews.get(i);
                    // 检查时间是否过期
                    if (interview.getInterviewEndTime().before(new Date())) {
                        // 更新状态为过期
                        LambdaUpdateWrapper<Interview> updateWrapper = new LambdaUpdateWrapper<>();
                        updateWrapper.eq(Interview::getInterviewId, interview.getInterviewId())
                                .set(Interview::getInterviewStatus, "已完成");
                        interviewMapper.update(null, updateWrapper);
                        interviews.remove(i);
                        i--; // 移除元素后，索引需要减 1
                    }
                }
            }

            interviews.forEach(interview -> {
                PageInterviewVO pageInterviewVO = BeanUtil.copyProperties(interview, PageInterviewVO.class);
                //查询出岗位
                LambdaQueryWrapper<Job> jobQueryWrapper = new LambdaQueryWrapper<>();
                jobQueryWrapper.eq(Job::getJobId, interview.getInterviewJobId());
                Job job = jobMapper.selectOne(jobQueryWrapper);
                pageInterviewVO.setJobTitle(job.getJobTitle());
                pageInterviewVO.setJobLocation(job.getJobLocation());
                pageInterviewVO.setJobType(job.getJobType());
                //查询出求职者的简历
                LambdaQueryWrapper<Resume> resumeQueryWrapper = new LambdaQueryWrapper<>();
                resumeQueryWrapper.eq(Resume::getResumeJobseekerId, interview.getInterviewJobseekerId());
                Resume resume = resumeMapper.selectOne(resumeQueryWrapper);
                pageInterviewVO.setResumeAge(resume.getResumeAge());
                pageInterviewVO.setResumeEducationMajor(resume.getResumeEducationMajor());
                pageInterviewVO.setResumeEducationSchool(resume.getResumeEducationSchool());
                pageInterviewVO.setResumeEducationDegree(resume.getResumeEducationDegree());
                pageInterviewVO.setResumeGender(resume.getResumeGender());
                pageInterviewVO.setResumeUsername(resume.getResumeUsername());
                //查询简历头像
                QueryWrapper<Image> imageQueryWrapper = new QueryWrapper<>();
                imageQueryWrapper.eq("image_name", "resume_avatar");
                imageQueryWrapper.eq("image_name_id", resume.getResumeId());
                Image image = imageMapper.selectOne(imageQueryWrapper);
                if (image != null) {
                    pageInterviewVO.setResumeAvatar(image.getImageUrl());
                }
                //添加到集合
                pageInterviewVOS.add(pageInterviewVO);
            });
        }
        //3.构建分页条件
        Page<PageInterviewVO> page = pageInterviewRequest.toPageDefaultSortByUpdateTime();
        return PageResponse.of(page, pageInterviewVOS);

    }

    @Override
    public InterviewVO getInterviewById(Long interviewId, String checkType) {
        //1.查询面试
        Interview interview = interviewMapper.selectById(interviewId);
        Job job = jobMapper.selectById(interview.getInterviewJobId());
        Employer employer = employerMapper.selectById(interview.getInterviewEmployerId());
        QueryWrapper<Resume> resumeQueryWrapper = new QueryWrapper<>();
        resumeQueryWrapper.eq("resume_jobseeker_id", interview.getInterviewJobseekerId());
        Resume resume = resumeMapper.selectOne(resumeQueryWrapper);
        //2.判断查询类型
        InterviewVO interviewVO;
        QueryWrapper<Image> imageQueryWrapper = new QueryWrapper<>();
        if ("jobseeker".equals(checkType)) {
            //求职者查询
            interviewVO = BeanCopyUtil.copyPropertiesToVo(interview, job, employer, InterviewVO.class);
            //查询出公司头像
            imageQueryWrapper.eq("image_name", "employer_avatar");
            imageQueryWrapper.eq("image_name_id", employer.getEmployerId());
            Image image = imageMapper.selectOne(imageQueryWrapper);
            if (image != null) {
                interviewVO.setUserAvatarUrl(image.getImageUrl());
            }
        } else {
            //企业查询
            interviewVO = BeanCopyUtil.copyPropertiesToVo(interview, job, resume, InterviewVO.class);
            //查询出简历头像
            imageQueryWrapper.eq("image_name", "resume_avatar");
            imageQueryWrapper.eq("image_name_id", resume.getResumeId());
            Image image = imageMapper.selectOne(imageQueryWrapper);
            if (image != null) {
                interviewVO.setResumeAvatar(image.getImageUrl());
            }
        }
        return interviewVO;
    }

    @Override
    public Boolean updateInterviewStatus(Long interviewId, String interviewStatus) {
        UpdateWrapper<Interview> interviewUpdateWrapper = new UpdateWrapper<>();
        interviewUpdateWrapper.eq("interview_id", interviewId);
        interviewUpdateWrapper.set("interview_status", interviewStatus);
        return interviewMapper.update(null, interviewUpdateWrapper) > 0;
    }
}




